<?php
/**
 * @copyright   Copyright (c) 2017 https://www.sapixx.com All rights reserved.
 * @license     Licensed (http://www.apache.org/licenses/LICENSE-2.0).
 * @author      pillar<ltmn@qq.com>
 * 行业分类
 */
namespace app\smartbc\controller;
use app\smartbc\model\SmartbcConfig;
use app\smartbc\model\SmartbcOrder;
use app\smartbc\model\SmartbcStoreGroup;
use app\smartbc\model\SmartbcStore;
use app\smartbc\model\SmartbcStoreUnion;
use think\Db;
use think\facade\Request;
use think\helper\Time;

class Group extends Common{

    /**
     * 列表
     */
    public function index(){
        $view['lists']    = SmartbcStoreGroup::where(['member_miniapp_id' => $this->member_miniapp_id])->order('id desc')->paginate(20);
        $view['pathMaps'] = [['name'=>'商圏管理','url'=> url("group/index")]];
        return $this->fetch()->assign($view);
    }

    /**
     * 已绑定商圏列表
     */
    public function storeIndex(int $id){
        $view['quan_id']  = $id;
        $view['lists']    = SmartbcStore::where($this->mini_program)->whereIn('id',SmartbcStoreUnion::where($this->mini_program)->where(['group_id' => $id])->column('store_id'))->order('id desc')->paginate(20);
        $view['pathMaps'] = [['name'=>'商圏管理','url'=> url("group/index")],['name'=>'商圈商户','url'=> url("group/storeindex",['id' => $id])]];
        return $this->fetch()->assign($view);
    }

    /**
     * 商圏列表
     */
    public function select(int $quan_id){
        $condition   = [];
        $condition[] = ['member_miniapp_id', '=', $this->member_miniapp_id];
        if(request()->isAjax()){
            $ids     = $this->request->param('ids');
            if(empty($ids)){
                return json(['code'=>0,'msg'=>'请选择要入住商圏的好店']);
            }
            $list = SmartbcStore::where($condition)->whereIn('id',$ids)->whereNotIn('id',SmartbcStoreUnion::where($this->mini_program)->where(['group_id'=>$quan_id,'type' => 0])->whereIn('store_id',$ids)->column('store_id'))->select();
            foreach ($list as $info){
                $config = SmartbcConfig::getConfig($this->member_miniapp_id);
                $member = SmartbcStoreUnion::where(['member_miniapp_id' => $this->member_miniapp_id,'group_id' => $quan_id,'type' => 0])->select();
                if(!empty($config->group_member) && count($member) >=$config->group_member){
                    return enjson(403,'商圈只能有'.$config->group_member.'个成员');
                }
                $size = SmartbcStoreUnion::where(['member_miniapp_id' => $this->member_miniapp_id,'store_id' => $info->id,'type' => 0])->select();
                if(!empty($config->group_join) && count($size) >=$config->group_join){
                    return enjson(403,'只能加入'.$config->group_join.'个商圈');
                }
                $union = SmartbcStoreUnion::where(['member_miniapp_id'=>$this->member_miniapp_id,'store_id' => $info->id,'group_id' => $quan_id,'type' => 1])->find();
                if($union){
                    $union->delete();
                }
                SmartbcStoreUnion::create(['member_miniapp_id'=>$this->member_miniapp_id,'store_id' => $info->id,'group_id' => $quan_id,'type' => 0,'create_time' => time(),'update_time' => time()]);
            }
            return json(['code'=>200,'msg'=>'好店入住商圏成功','data' =>[]]);
        }else{
            $keyword  = $this->request->param('keyword');
            if(!empty($keyword)) {
                $condition[] = ['name', 'like', '%' . $keyword . '%'];
            }
            $view['lists']   = SmartbcStore::where($condition)->whereNotIn('id',SmartbcStoreUnion::where($this->mini_program)->where(['group_id'=>$quan_id,'type' => 0])->column('store_id'))->order('id desc')->paginate(20);
            $view['keyword'] = $keyword;
            $view['quan_id'] = $quan_id;
            return $this->fetch()->assign($view);
        }
    }

    //编辑
    public function edit(){
        if(request()->isAjax()){
            $param = [
                'id'      => $this->request->param('id/d', 0),
                'title'   => $this->request->param('title/s'),
                'content' => $this->request->param('content/s'),
                'uid'     => $this->request->param('uid/d'),
            ];
            $validate = $this->validate($param,'Group.edit');
            if(true !== $validate){
                return json(['code'=>0,'msg'=>$validate]);
            }
            $result =  SmartbcStoreGroup::where(['member_miniapp_id' => $this->member_miniapp_id,'id' =>  $param['id']])->find();
            if($result){
                $result->title   = $param['title'];
                $result->content = $param['content'];
                $result->uid     = $param['uid'];
                $result->save();
            }else{
                $info =  SmartbcStoreGroup::where(['member_miniapp_id' => $this->member_miniapp_id,'uid' =>  $param['uid']])->find();
                if($info){
                    return json(['code'=>403,'msg'=>'只能管理一个商圈']);
                }
                $param['member_miniapp_id'] = $this->member_miniapp_id;
                SmartbcStoreGroup::create($param);
            }
            return json(['code'=>200,'url'=>url('group/index'),'msg'=>'操作成功']);
        }else{
            $view['info']= SmartbcStoreGroup::where(['id' => $this->request->param('id/d',0),'member_miniapp_id' => $this->member_miniapp_id])->find();
            return $this->fetch()->assign($view);
        }
    }

    //删除商圈
    public function delete(int $id){
        $store = SmartbcStoreGroup::where(['member_miniapp_id' => $this->member_miniapp_id])->whereIn('id',SmartbcStoreUnion::where($this->mini_program)->where(['group_id' => $id,'type' => 0])->column('group_id'))->find();
        if($store){
            return json(['code'=>403,'msg'=>'删除失败,商圏中还包含店铺']);
        }
        $result = SmartbcStoreGroup::destroy($id);
        if($result){
            return json(['code'=>200,'msg'=>'操作成功']);
        }else{
            return json(['code'=>403,'msg'=>'删除失败']);
        } 
    }

    //从商圏中删除好店
    public function deleteStore(int $id,$quan_id){
        $result = SmartbcStoreUnion::destroy(['store_id' => $id,'group_id' => $quan_id]);
        if($result){
            return json(['code'=>200,'msg'=>'操作成功']);
        }
        return json(['code'=>403,'msg'=>'删除失败']);
    }

    /**
     * 商圏用户订单
     * @access public
     */
    public function order(int $state = 1,int $group_id){
        $condition   = [];
        $condition[] = ['member_miniapp_id', '=', $this->member_miniapp_id];
        $condition[] = ['group_id', '=', $group_id];
        $store_id    = Request::param('store_id/d', '');
        $store_name  = Request::param('store_name');
        if ($store_id) {
            $condition[] = ['store_id', '=', $store_id];
        }
        $time = Request::param('time/d',0);
        if($time){
            switch ($time) {
                case 2:
                    list($start, $end) = Time::yesterday();
                    break;
                case 30:
                    list($start, $end) = Time::month();
                    break;
                case 60:
                    list($start, $end) = Time::lastMonth();
                    break;
                default:
                    list($start, $end) = Time::today();
                    break;
            }
            $condition[] = ['paid_time','>=',$start];
            $condition[] = ['paid_time','<=',$end];
        }
        $starttime = Request::param('starttime/s');
        $endtime   = Request::param('endtime/s');
        if($starttime){
            $condition[] = ['paid_time','>=',strtotime($starttime)];
        }
        if($endtime){
            $condition[] = ['paid_time','<=',strtotime($endtime)];
        }
        $view['orders']          = SmartbcOrder::where(['state' => $state ? 1 : 0])->whereIn('store_id',SmartbcStoreUnion::where($condition)->column('store_id'))->order('id desc')->paginate(20, false, ['query' => ['store_id' => $store_id, 'store_name' => $store_name, 'time' => $time, 'starttime' => $starttime, 'endtime' => $endtime, 'group_id' => $group_id]]);
        $view['order_num']       = SmartbcOrder::where(['state' => 1])->whereIn('store_id',SmartbcStoreUnion::where($condition)->column('store_id'))->count();
        $view['user_amount']     = SmartbcOrder::where(['state' => 1])->whereIn('store_id',SmartbcStoreUnion::where($condition)->column('store_id'))->sum('amount');
        $view['order_amount']    = SmartbcOrder::where(['state' => 1])->whereIn('store_id',SmartbcStoreUnion::where($condition)->column('store_id'))->sum('price');
        $view['coupon_price']    = money($view['user_amount'] - $view['order_amount']);
        $view['time']            = $time;
        $view['starttime']       = $starttime;
        $view['endtime']         = $endtime;
        $view['store_id']        = $store_id;
        $view['group_id']        = $group_id;
        $view['store_name']      = $store_name;
        return view()->assign($view);
    }
}